<template>
    <div class="profile">
        <el-card>
            <template #header>
                <div class="card-header">
                    <h3>个人资料</h3>
                    <el-button type="primary" @click="handleEdit" v-if="!isEditing">
                        编辑资料
                    </el-button>
                    <el-button-group v-else>
                        <el-button type="primary" @click="handleSave">保存</el-button>
                        <el-button @click="handleCancel">取消</el-button>
                    </el-button-group>
                </div>
            </template>

            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" :disabled="!isEditing">
                <el-form-item label="头像">
                    <div class="avatar-uploader">
                        <div class="avatar-preview" @click="isEditing && triggerFileInput()">
                            <img v-if="form.avatar && form.avatar !== ' '" :src="form.avatar.startsWith('data:') ? form.avatar : getImageUrl(form.avatarFilename || form.avatar, form.avatarType || 'user')" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                            <div v-if="isEditing" class="avatar-overlay">
                                <el-icon><Camera /></el-icon>
                                <span>更换头像</span>
                            </div>
                        </div>
                        <input 
                            ref="fileInputRef"
                            type="file" 
                            accept="image/jpeg,image/png" 
                            style="display: none" 
                            @change="handleFileChange"
                        />
                    </div>
                </el-form-item>

                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="form.nickname" />
                </el-form-item>

                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="form.gender">
                        <el-radio label="male">男</el-radio>
                        <el-radio label="female">女</el-radio>
                        <el-radio label="other">其他</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="生日" prop="birthday">
                    <el-date-picker v-model="form.birthday" type="date" placeholder="选择日期" style="width: 100%" />
                </el-form-item>

                <el-form-item label="学校" prop="school">
                    <el-select v-model="form.school" placeholder="请选择学校" style="width: 100%">
                        <el-option v-for="item in schools" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="专业" prop="major">
                    <el-input v-model="form.major" />
                </el-form-item>

                <el-form-item label="年级" prop="grade">
                    <el-select v-model="form.grade" placeholder="请选择年级" style="width: 100%">
                        <el-option v-for="item in grades" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="个人简介" prop="bio">
                    <el-input v-model="form.bio" type="textarea" :rows="4" placeholder="介绍一下自己吧" />
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { Plus, Camera } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { getImageUrl } from '@/utils/image'

const userStore = useUserStore()
const formRef = ref<FormInstance>()
const isEditing = ref(false)

// 表单数据
const form = reactive({
    id: null,
    avatar: ' ',
    avatarFilename: ' ',
    avatarType: 'user',
    nickname: userStore.userInfo.nickname,
    gender: userStore.userInfo.gender,
    birthday: userStore.userInfo.birthday,
    school: userStore.userInfo.school,
    major: userStore.userInfo.major,
    grade: userStore.userInfo.grade,
    bio: userStore.userInfo.bio
})

// 表单验证规则
const rules = reactive<FormRules>({
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    school: [
        { required: true, message: '请选择学校', trigger: 'change' }
    ],
    major: [
        { required: true, message: '请输入专业', trigger: 'blur' }
    ],
    grade: [
        { required: true, message: '请选择年级', trigger: 'change' }
    ]
})

// 学校列表
const schools = [
    { id: 1, name: '北京大学' },
    { id: 2, name: '清华大学' },
    { id: 3, name: '复旦大学' },
    { id: 4, name: '浙江大学' }
]

// 年级列表
const grades = [
    { value: 'freshman', label: '大一' },
    { value: 'sophomore', label: '大二' },
    { value: 'junior', label: '大三' },
    { value: 'senior', label: '大四' },
    { value: 'graduate', label: '研究生' }
]

// 头像上传相关
const fileInputRef = ref<HTMLInputElement | null>(null);

// 触发文件选择框
const triggerFileInput = () => {
    if (fileInputRef.value) {
        fileInputRef.value.click();
    }
};

// 处理文件选择
const handleFileChange = (e: Event) => {
    const input = e.target as HTMLInputElement;
    const file = input.files?.[0];
    
    if (!file) return;
    
    const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;
    
    if (!isJPGOrPNG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
        return;
    }
    
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
        return;
    }
    
    // 保存文件对象
    form.avatarFile = file;
    
    // 创建预览
    const reader = new FileReader();
    reader.onload = (evt) => {
        if (evt.target?.result) {
            form.avatar = evt.target.result as string;
        }
    };
    reader.readAsDataURL(file);
    
    ElMessage.success('头像已选择，保存后将上传');
};

// 处理编辑
const handleEdit = () => {
    isEditing.value = true
}

// 处理保存
const handleSave = async () => {
    if (!formRef.value) return;

    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 处理提交的数据
                const submitData = { ...form };
                
                // 确保生日字段有合适的值
                if (!submitData.birthday || submitData.birthday === 'null') {
                    submitData.birthday = '';
                }
                
                // 提交表单，包含文件
                await userStore.updateUserInfo(submitData);
                ElMessage.success('保存成功');
                isEditing.value = false;
            } catch (error) {
                ElMessage.error('保存失败');
            }
        }
    });
};

// 处理取消
const handleCancel = () => {
    // 重置表单数据
    Object.assign(form, userStore.userInfo)
    isEditing.value = false
}

// 在 onMounted 或获取用户信息后，如果 avatar 字段存的是文件名
onMounted(async () => {
    // ... 获取用户信息 lógica ...
    if (userStore.userInfo.avatarFilename) {
        form.avatarFilename = userStore.userInfo.avatarFilename
        form.avatarType = userStore.userInfo.avatarType || 'user'
        form.avatar = getImageUrl(userStore.userInfo.avatarFilename, userStore.userInfo.avatarType)
    } else if (userStore.userInfo.avatar) {
        form.avatar = userStore.userInfo.avatar.startsWith('http') || userStore.userInfo.avatar.startsWith('/') ? userStore.userInfo.avatar : getImageUrl(userStore.userInfo.avatar, 'user')
    }
    // ...
})

// 在提交表单时，应该提交 form.value.avatarFilename 给后端
// const submitForm = async () => {
//   // ...
//   const payload = {
//     ...form.value,
//     avatar: form.value.avatarFilename, // 确保后端接口接收的是文件名
//   };
//   delete payload.avatarFilename; // 清理辅助字段
//   delete payload.avatarType;
//   // ... call api ...
// };
</script>

<style scoped>
.profile {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header h3 {
    margin: 0;
    font-size: 18px;
    color: #333;
}

.avatar-uploader {
    text-align: center;
}

.avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    object-fit: cover;
}

.avatar-uploader .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
}

.avatar-uploader .avatar-uploader-icon:hover {
    border-color: #409eff;
}

.avatar-preview {
    position: relative;
    display: inline-block;
    cursor: pointer;
}

.avatar-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.avatar-overlay .el-icon {
    color: #fff;
    font-size: 20px;
}

.role-button .el-icon {
  margin-right: 5px;
}
</style>